package com.huawei.chengdu.meetingdemo.view;

import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.device.idea.meeting.Addressbook.model.AddrBookNetUserInfo;
import com.device.idea.meeting.Addressbook.model.AddrBookNormal;
import com.device.idea.meeting.Addressbook.model.AddrBookUserInfo;
import com.device.idea.meeting.AppInfo;
import com.device.idea.meeting.CallCtrl.model.ConfState;
import com.device.idea.meeting.CallRecord.model.CallRecordInfo;
import com.device.idea.meeting.CallRecord.model.CallRecordList;
import com.device.idea.meeting.ConfManage.model.BookConfInfo;
import com.device.idea.meeting.ConfManage.model.ConfInfo;
import com.device.idea.meeting.ConfManage.model.ConfOptionalInfo;
import com.device.idea.meeting.FlexibleLayout.model.FlexibleLayout;
import com.device.idea.meeting.MultiStream.model.LayoutInfo;
import com.device.idea.meeting.MultiStream.model.LayoutSubWindow;
import com.device.idea.meeting.MultiStream.model.StreamType;
import com.device.idea.meeting.Share.model.ShareCurInfo;
import com.huawei.chengdu.meetingdemo.R;
import com.huawei.chengdu.meetingdemo.callback.MeetingCallbackSelf;
import com.huawei.chengdu.meetingdemo.callback.MeetingControlEventCallback;
import com.huawei.chengdu.meetingdemo.consts.ConfConst;
import com.huawei.chengdu.meetingdemo.presenter.ConfSdkPresenter;
import com.huawei.chengdu.meetingdemo.presenter.MeetingManager;
import com.huawei.chengdu.meetingdemo.util.CallTimeUtils;
import com.huawei.chengdu.meetingdemo.util.LogUtil;
import com.huawei.chengdu.meetingdemo.util.StringUtil;
import com.huawei.chengdu.meetingdemo.view.adapter.BookConfAdapter;
import com.huawei.chengdu.meetingdemo.view.adapter.CallRecordListAdapter;
import com.huawei.chengdu.meetingdemo.view.adapter.NetContactListAdapter;
import com.huawei.chengdu.meetingdemo.view.adapter.LocalContactListAdapter;
import com.huawei.chengdu.meetingdemo.view.dialogs.ConfSettingDialog;
import com.huawei.chengdu.meetingdemo.view.dialogs.IncomingCallDialog;
import com.huawei.chengdu.meetingdemo.view.dialogs.ModifyContactDialog;
import com.huawei.chengdu.meetingdemo.view.dialogs.NoLicenseDialog;
import com.huawei.chengdu.meetingdemo.view.dialogs.RequestFloatPermissionDialog;
import com.huawei.chengdu.meetingdemo.view.dialogs.SiteCallSettingDialog;
import com.huawei.chengdu.meetingdemo.view.dialogs.StartCallDialog;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会议DEMO会前主界面
 *
 * @author L00354002
 * @since 2022-8-16
 */
public class HomeActivity extends FragmentActivity {
    public static volatile boolean isInForeground = false;
    private EditText userInputConfId;
    private static final String TAG = HomeActivity.class.getSimpleName();
    private EditText searchContactName;
    private ImageView beginSearchContact;
    private ImageView deleteAllInput;
    private Button startCallButton;
    private Button confCreateButton;
    private ImageView siteCallSettings;
    private TextView confSetting;
    private TextView confListEmptyHint;
    private TextView contactListEmptyHint;
    private TextView callRecordEmptyHint;
    private TextView callRecordClear;
    private RecyclerView bookConfList;
    private RecyclerView contactListLocal;
    private RecyclerView contactListCompany;
    private RecyclerView callRecordList;
    private RadioGroup contactTypeSwitch;
    private ImageView localContactAdd;
    private View inMeetingView;
    private MeetingControlView meetingControlView;
    private BookConfAdapter bookConfAdapter;
    private LocalContactListAdapter localContactListAdapter;
    private NetContactListAdapter netContactListAdapter;
    private CallRecordListAdapter callRecordListAdapter;
    private List localContactList;
    private List companyContactList;
    private StartCallDialog startCallDialog;
    private IncomingCallDialog incomingCallDialog;
    private InMeetingFragmentFixed inMeetingFragmentFixed;
    private InMeetingFragmentFlexible inMeetingFragmentFlexible;
    private MeetingPresentation meetingPresentation;
    private SiteCallSettingDialog siteCallSettingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initLog();
        LogUtil.info(TAG + " onCreate");
        initSdk();
        initView();
        initListener();
        initData();
        requestRight();
    }

    private void requestRight() {
        if (!Settings.canDrawOverlays(this)) {
            RequestFloatPermissionDialog requestFloatPermissionDialog = new RequestFloatPermissionDialog(this);
            requestFloatPermissionDialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        LogUtil.info(TAG + " onDestroy");
        release();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        LogUtil.info(TAG + " onResume");
        isInForeground = true;
        super.onResume();
    }

    @Override
    protected void onStop() {
        LogUtil.info(TAG + " onStop");
        isInForeground = false;
        super.onStop();
    }

    private void release() {
        dismissAllDialog();
        if (MeetingManager.getInstance().isInConf()) {
            ConfSdkPresenter.leaveConf();
        }
        ConfSdkPresenter.destroySdk(this);
    }

    private void initLog() {
        try {
            String logDir = this.getFilesDir().getCanonicalPath() + File.separator + "log";
            LogUtil.setLogPath(logDir);
        } catch (IOException e) {
            LogUtil.error("Invalid file");
        }
    }

    private void initSdk() {
        AppInfo appInfo = new AppInfo(getPackageName(), getPackageName(), ConfConst.PID);
        MeetingControlEventCallback eventCallback = new MeetingControlEventCallback(this);
        ConfSdkPresenter.initSdkController(getBaseContext(), appInfo, eventCallback);
        ConfSdkPresenter.setUiInstance(this);
    }

    private void initView() {
        userInputConfId = findViewById(R.id.user_input_confid);
        startCallButton = findViewById(R.id.start_call);
        confCreateButton = findViewById(R.id.conf_create);
        confSetting = findViewById(R.id.conf_setting);
        siteCallSettings = findViewById(R.id.site_call_settings);
        confListEmptyHint = findViewById(R.id.conf_list_empty_hint);
        contactListEmptyHint = findViewById(R.id.contact_list_empty_hint);
        callRecordEmptyHint = findViewById(R.id.recent_list_empty_hint);
        contactTypeSwitch = findViewById(R.id.contact_type_switch);
        callRecordClear = findViewById(R.id.recent_call_clear);
        localContactAdd = findViewById(R.id.local_contact_add);
        inMeetingView = findViewById(R.id.in_meeting_fragment);
        searchContactName = findViewById(R.id.search_contact_name);
        beginSearchContact = findViewById(R.id.begin_contact_search);
        deleteAllInput = findViewById(R.id.delete_all_input);

        bookConfList = findViewById(R.id.book_conf_list);
        bookConfAdapter = new BookConfAdapter(new ArrayList<>());
        bookConfList.setAdapter(bookConfAdapter);
        bookConfList.setLayoutManager(new LinearLayoutManager(this));

        contactListLocal = findViewById(R.id.local_contact_list);
        localContactListAdapter = new LocalContactListAdapter(this);
        contactListLocal.setAdapter(localContactListAdapter);
        contactListLocal.setLayoutManager(new LinearLayoutManager(this));

        contactListCompany = findViewById(R.id.company_contact_list);
        netContactListAdapter = new NetContactListAdapter();
        contactListCompany.setAdapter(netContactListAdapter);
        contactListCompany.setLayoutManager(new LinearLayoutManager(this));

        callRecordList = findViewById(R.id.recent_list);
        callRecordListAdapter = new CallRecordListAdapter();
        callRecordList.setAdapter(callRecordListAdapter);
        callRecordList.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (!ConfSdkPresenter.isSupportOnPremisesConf()) {
                    NoLicenseDialog noLicenseDialog = new NoLicenseDialog(HomeActivity.this);
                    noLicenseDialog.show();
                }
                ConfSdkPresenter.getVersion();

                ConfSdkPresenter.searchAllLocalUsers(new MeetingCallbackSelf<List<AddrBookUserInfo>>(TAG + " searchAllUsers") {
                    // 统一在MeetingControlEventCallback中处理，这里不重复处理
                    @Override
                    public void onSuccess(List<AddrBookUserInfo> addrBookUserInfos) {
                    }

                    @Override
                    public void onFailed(int errCode, String errMsg) {
                    }
                }.getMeetingCallback());
                ConfSdkPresenter.getCallRecord();
                ConfSdkPresenter.searchCompanyUsers("*", new MeetingCallbackSelf<List<AddrBookNetUserInfo>>(TAG + " searchNetAddressBookInfo") {
                    // 统一在MeetingControlEventCallback中处理，这里不重复处理
                    @Override
                    public void onSuccess(List<AddrBookNetUserInfo> addrBookNetUserInfos) {
                    }

                    @Override
                    public void onFailed(int errCode, String errMsg) {
                    }
                }.getMeetingCallback());
                ConfSdkPresenter.searchConfList();
            }
        }).start();
    }

    private void initListener() {
        startCallButton.setOnClickListener(v -> startCallHandle());
        confCreateButton.setOnClickListener(v -> createConf());
        confSetting.setOnClickListener(v -> confSettingClickHandle());
        contactTypeSwitch.setOnCheckedChangeListener(((group, checkedId) -> contactTypeChangeHandle(checkedId)));
        callRecordClear.setOnClickListener(v -> ConfSdkPresenter.clearCallRecord());
        localContactAdd.setOnClickListener(v -> localContactAddHandle());
        beginSearchContact.setOnClickListener(v -> searchContact());
        deleteAllInput.setOnClickListener(v -> searchContactName.setText(""));
        siteCallSettings.setOnClickListener(v -> siteCallSettingHandle());
    }

    private void startCallHandle() {
        String callNum = userInputConfId.getText().toString();
        if (callNum.length() == 0) {
            Toast.makeText(this, "输入不能为空", Toast.LENGTH_LONG).show();
        }
        if (StringUtil.checkString(callNum)) {
            ConfSdkPresenter.startCall(callNum);
        } else {
            Toast.makeText(this, "号码超长或存在非法字符", Toast.LENGTH_LONG).show();
        }
    }

    // 主叫呼集
    private void createConf() {
        // 将本地通讯录选中者与网络通讯录选中者合并
        List<AddrBookUserInfo> totalSelectedContact = new ArrayList<>(localContactListAdapter.selectedContactList);
        totalSelectedContact.addAll(netContactListAdapter.selectedContactList.stream().map(addrBookNetUserInfo -> {
            AddrBookUserInfo userInfo = new AddrBookUserInfo();
            userInfo.setId(0);
            userInfo.setName(addrBookNetUserInfo.getName());
            userInfo.setDeviceType(addrBookNetUserInfo.getDeviceType());
            userInfo.setLineType(addrBookNetUserInfo.getLineType());
            AddrBookNormal addrBookNormal = new AddrBookNormal();
            addrBookNormal.setCallRate(ConfConst.DFT_CALL_WIDTH);
            addrBookNormal.setSiteNumber(addrBookNetUserInfo.getLineInfo().getSiteNumber());
            addrBookNormal.setIp(addrBookNetUserInfo.getLineInfo().getIp());
            addrBookNormal.setUrl(addrBookNetUserInfo.getLineInfo().getUrl());
            userInfo.setLineInfo(addrBookNormal);
            return userInfo;
        }).collect(Collectors.toList()));

        int sitCount = 1 + totalSelectedContact.size();
        if (sitCount > ConfConst.MAX_SIT_COUNT) {
            Toast.makeText(this, "会场数目不超过400个", Toast.LENGTH_LONG).show();
            return;
        }
        ConfInfo confInfo = new ConfInfo();
        confInfo.setName("PreConf-" + CallTimeUtils.getCreateTime());
        confInfo.setSiteInfo(totalSelectedContact);
        ConfOptionalInfo info = new ConfOptionalInfo();
        info.setVideoAnonymousSiteNum(3);  // 可选参数 预留视频会议资源数  默认3
        info.setAudioAnonymousSiteNum(0);  // 可选参数 预留音频会议资源数 默认0
        info.setPassWord(SiteCallSettingDialog.confPassword);
        info.setEncryptionPolicy(SiteCallSettingDialog.encryptMode); // 默认自动加密
        info.setCallRate(SiteCallSettingDialog.bandWidth);
        confInfo.setOptionalInfo(info);
        ConfSdkPresenter.createConf(confInfo);
    }

    private void siteCallSettingHandle() {
        if (siteCallSettingDialog == null) {
            siteCallSettingDialog = new SiteCallSettingDialog(this);
        }
        siteCallSettingDialog.show();
    }

    public void showStartCallDialog(String callNumber) {
        startCallDialog = new StartCallDialog(this, callNumber);
        startCallDialog.show();
    }

    private void confSettingClickHandle() {
        ConfSettingDialog confSettingDialog = new ConfSettingDialog(this);
        confSettingDialog.show();
    }

    private void localContactAddHandle() {
        ModifyContactDialog modifyContactDialog = new ModifyContactDialog(this);
        modifyContactDialog.show();
    }

    private void contactTypeChangeHandle(int checkedId) {
        LogUtil.debug("ContactType changed, type = " + checkedId);
        if (checkedId == R.id.contact_type_company) {
            contactListLocal.setVisibility(View.GONE);
            localContactAdd.setVisibility(View.GONE);
            contactListCompany.setVisibility(View.VISIBLE);
        } else {
            contactListLocal.setVisibility(View.VISIBLE);
            localContactAdd.setVisibility(View.VISIBLE);
            contactListCompany.setVisibility(View.GONE);
        }
    }

    public void initBookConfInfo(List<BookConfInfo> bookConfInfos) {
        confListEmptyHint.post(() -> {
            confListEmptyHint.setVisibility(bookConfInfos.size() > 0 ? View.GONE : View.VISIBLE);
            bookConfAdapter.updateConfInfoList(bookConfInfos);
        });
    }

    public void initLocalContact(List<AddrBookUserInfo> addrBookUserInfos) {
        runOnUiThread(() -> {
            localContactList = addrBookUserInfos;
            localContactListAdapter.updateContactList(addrBookUserInfos);
            updateContactEmptyHint();
        });
    }

    public void initCompanyContact(List<AddrBookNetUserInfo> userInfoList) {
        runOnUiThread(() -> {
            companyContactList = userInfoList;
            netContactListAdapter.updateContactList(userInfoList);
            updateContactEmptyHint();
        });
    }

    public void initCallRecord(CallRecordList callRecordList) {
        runOnUiThread(() -> {
            List<CallRecordInfo> callRecordInfoList = new ArrayList<>();
            callRecordInfoList.addAll(callRecordList.getCallAcceptRecord());
            callRecordInfoList.addAll(callRecordList.getCallNoAnsRecord());
            callRecordInfoList.addAll(callRecordList.getCallOutRecord());
            callRecordInfoList.sort((o1, o2) -> CallTimeUtils.callTimeToSecond(o2.getStartTime()) - CallTimeUtils.callTimeToSecond(o1.getStartTime()));

            callRecordEmptyHint.setVisibility(callRecordInfoList.size() > 0 ? View.GONE : View.VISIBLE);
            callRecordListAdapter.updateCallRecordList(callRecordInfoList);
        });
    }

    private void updateContactEmptyHint() {
        boolean isShow;
        if (contactTypeSwitch.getCheckedRadioButtonId() == R.id.contact_type_local) {
            isShow = localContactList == null || localContactList.size() == 0;
        } else {
            isShow = companyContactList == null || companyContactList.size() == 0;
        }
        contactListEmptyHint.post(() -> {
            contactListEmptyHint.setVisibility(isShow ? View.VISIBLE : View.GONE);
        });
    }

    private void searchContact() {
        String searchName = searchContactName.getText().toString();
        if (contactTypeSwitch.getCheckedRadioButtonId() == R.id.contact_type_local) {
            if (searchName.isEmpty()) {
                ConfSdkPresenter.searchAllLocalUsers(new MeetingCallbackSelf<List<AddrBookUserInfo>>(TAG + " searchAllUsers") {
                    // 统一在MeetingControlEventCallback中处理，这里不重复处理
                    @Override
                    public void onSuccess(List<AddrBookUserInfo> addrBookUserInfos) {
                    }

                    @Override
                    public void onFailed(int errCode, String errMsg) {
                    }
                }.getMeetingCallback());
                return;
            }
            ConfSdkPresenter.searchLocalUserByKeyword(searchName, new MeetingCallbackSelf<List<AddrBookUserInfo>>(TAG + " searchUserByKeyWord") {
                // 统一在MeetingControlEventCallback中处理，这里不重复处理
                @Override
                public void onSuccess(List<AddrBookUserInfo> addrBookUserInfos) {
                }

                @Override
                public void onFailed(int errCode, String errMsg) {
                }
            }.getMeetingCallback());
        } else {
            ConfSdkPresenter.searchCompanyUsers(searchName.isEmpty() ? "*" : searchName, new MeetingCallbackSelf<List<AddrBookNetUserInfo>>(TAG + " searchNetAddressBookInfo") {
                // 统一在MeetingControlEventCallback中处理，这里不重复处理
                @Override
                public void onSuccess(List<AddrBookNetUserInfo> addrBookNetUserInfos) {
                }

                @Override
                public void onFailed(int errCode, String errMsg) {
                }
            }.getMeetingCallback());
        }
    }

    public void incomingCall(String displayName, String calleeNumber) {
        String callName = displayName == null || displayName.length() == 0 ? calleeNumber : displayName;
        runOnUiThread(() -> {
            incomingCallDialog = new IncomingCallDialog(this);
            incomingCallDialog.setIncomingCallNum(callName);
            incomingCallDialog.show();
        });
    }

    public void dismissStartCallDialog() {
        if (startCallDialog != null) {
            runOnUiThread(() -> {
                startCallDialog.dismiss();
            });
        }
    }

    public void dismissIncominngCallDialog() {
        if (incomingCallDialog != null) {
            runOnUiThread(() -> {
                incomingCallDialog.dismiss();
            });
        }
    }

    public void dismissAllDialog() {
        dismissStartCallDialog();
        dismissIncominngCallDialog();
    }

    public void handleLayoutChangeNotify(LayoutInfo layoutInfo) {
        List<LayoutSubWindow> layoutSubWindows = layoutInfo.getWindowsInfo().getSubWindows();

        // 会中APP切到后台，点击小卡片时，需自行拉起应用
        if (!isInForeground && ConfConst.TARGET_STEAM_TYPE.contains(layoutSubWindows.get(0).getStreamType())) {
            awakeSelf();
        }

        // 判断布局变化通知是否需要处理
        if (!isDeal(layoutSubWindows)) {
            return;
        }
        if (layoutInfo.getScreenInfo().isPrimary()) {
            handlePrimaryScreen(layoutInfo);  // 主屏布局处理
        } else {
            handlePresentation(layoutInfo);   // 辅屏布局处理
        }
    }

    private void handlePrimaryScreen(LayoutInfo layoutInfo) {
        runOnUiThread(() -> {
            inMeetingView.setVisibility(View.VISIBLE);
            // 已在会议中，由会中fragment处理
            if (inMeetingFragmentFixed != null) {
                inMeetingFragmentFixed.setLayoutInfo(layoutInfo);
                inMeetingFragmentFixed.handleLayoutChangeNotify();
                return;
            }
            // 不在会议中，启动会中fragment
            inMeetingFragmentFixed = new InMeetingFragmentFixed(layoutInfo);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.in_meeting_fragment, inMeetingFragmentFixed)
                    .commit();
        });
    }

    private boolean isDeal(List<LayoutSubWindow> layoutSubWindows) {
        // 1.当前是灵活布局，收到固定布局通知不处理
        if (inMeetingFragmentFlexible != null) {
            LogUtil.info("Current is flexible Layout, not need deal");
            return false;
        }
        // 2.布局通知中的流类型非目标流类型
        int streamCount = layoutSubWindows.size();
        StreamType firstStreamType = layoutSubWindows.get(0).getStreamType();
        StreamType secondStreamType = StreamType.STREAM_INVAILD;
        if (streamCount > 1) {
            secondStreamType = layoutSubWindows.get(1).getStreamType();
        }
        if (!ConfConst.TARGET_STEAM_TYPE.contains(firstStreamType) && !ConfConst.TARGET_STEAM_TYPE.contains(secondStreamType) ) {
            LogUtil.info("The stream type not in target, not need deal");
            return false;
        }
        LogUtil.info("The LayoutInfo need deal");
        return true;
    }

    private void handlePresentation(LayoutInfo layoutInfo) {
        if (layoutInfo.getScreenInfo().isCloned()) { // 克隆场景关闭辅屏显示
            if (meetingPresentation != null && meetingPresentation.isShowing()) {
                meetingPresentation.dismiss();
            }
            return;
        }
        if (meetingPresentation != null) {
            meetingPresentation.setLayoutInfo(layoutInfo);
            meetingPresentation.handleLayoutChangeNotify();
            return;
        }

        DisplayManager displayManager = (DisplayManager) getSystemService(DISPLAY_SERVICE);
        Display[] displays = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION);
        if (displays.length == 0) {
            LogUtil.error("Displays size = 0");
            return;
        }
        runOnUiThread(() -> {
            meetingPresentation = new MeetingPresentation(this, displays[0], layoutInfo);
            meetingPresentation.show();
        });
    }

    public void handleFlexibleLayoutChangeNotify(List<FlexibleLayout> list) {
        StreamType streamType = StreamType.valueOf(list.get(0).getStreamType());
        // 处理五种流： 本主、远主、远辅、本地有线投屏、本地无线投屏
        if (!ConfConst.TARGET_STEAM_TYPE.contains(streamType)) {
            LogUtil.info("The stream type not need deal");
            return;
        }

        // 会中APP切到后台，点击小卡片时，需自行拉起应用
        if (!isInForeground) {
            awakeSelf();
        }

        runOnUiThread(() -> {
            inMeetingView.setVisibility(View.VISIBLE);
            // 已在会议中，由会中fragment处理
            if (inMeetingFragmentFlexible != null) {
                inMeetingFragmentFlexible.setFlexibleLayout(list);
                inMeetingFragmentFlexible.handleFlexibleLayoutChangeNotify();
                return;
            }
            // 不在会议中，启动会中fragment
            inMeetingFragmentFlexible = new InMeetingFragmentFlexible(list);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.in_meeting_fragment, inMeetingFragmentFlexible)
                    .commit();
        });
    }

    public void handleConfStateChange(ConfState confState) {
        MeetingManager.getInstance().onConfStateChangeNotify(confState);
        // 入会后将呼叫弹窗隐藏
        if (confState == ConfState.CONF) {
            dismissStartCallDialog();
            // 创建会控栏View
            if (meetingControlView == null) {
                meetingControlView = new MeetingControlView(this);
            }
        }

        // 离会后将会中UI隐藏
        if (confState == ConfState.NONE) {
            inMeetingView.setVisibility(View.GONE);
            inMeetingFragmentFixed = null;
            inMeetingFragmentFlexible = null;
        }
    }

    public void handleShareStateChange(ShareCurInfo shareCurInfo) {

    }

    public void observeAudioToVideo(boolean isShow) {
        if (meetingControlView == null) {
            LogUtil.error(TAG + " observeAudioToVideo,meetingControlView is null");
            return;
        }
        meetingControlView.observeAudioToVideo(isShow);
    }

    private void awakeSelf() {
        LogUtil.info("Begin awake HomeActivity");
        Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        while (!isInForeground) {
        } // 等activity在界面显示后再绑定UI
    }
}